package com.program.facesigninsystem.face;

import com.arcsoft.face.*;
import com.arcsoft.face.enums.*;
import com.arcsoft.face.toolkit.ImageInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.arcsoft.face.toolkit.ImageFactory.getRGBData;

/**
 * @author Mapler
 */
public class ArcSoftFace {
    private  FaceEngine faceEngine = new FaceEngine("C:\\FaceSystem\\lib\\WIN64");

    public ArcSoftFace(){
        init();
    }

    /***
     * 激活人脸识别引擎
     * @return 返回错误码
     */
        public int activeOnline(){
            final  String appId = "Aq1NsjmJnG7GqJnr7pb1QQ8WaLVWYRURDQ7YQkjjJra4";
            final  String sdkKey = "DF2UYiFC5ZdpTQ8EKARcqNgqquUbB42cdbgj5xxpq5rC";
            int errorCode = faceEngine.activeOnline(appId, sdkKey);
            if (errorCode != ErrorInfo.MOK.getValue() && errorCode != ErrorInfo.MERR_ASF_ALREADY_ACTIVATED.getValue())
            {
                System.out.println("引擎激活失败");
            }
            return errorCode;
        }

    /***
     * 初始化人脸识别引擎
     */
    private void init(){
            EngineConfiguration engineConfiguration = new EngineConfiguration();
            //引擎配置
            engineConfiguration.setDetectMode(DetectMode.ASF_DETECT_MODE_IMAGE);
            engineConfiguration.setDetectFaceOrientPriority(DetectOrient.ASF_OP_0_ONLY);
            engineConfiguration.setDetectFaceMaxNum(50);
            engineConfiguration.setDetectFaceScaleVal(16);
            //功能配置
            FunctionConfiguration functionConfiguration = new FunctionConfiguration();
            functionConfiguration.setSupportAge(false);
            functionConfiguration.setSupportFace3dAngle(false);
            functionConfiguration.setSupportFaceDetect(true);
            functionConfiguration.setSupportFaceRecognition(true);
            functionConfiguration.setSupportGender(false);
            functionConfiguration.setSupportLiveness(true);
            functionConfiguration.setSupportIRLiveness(true);
            engineConfiguration.setFunctionConfiguration(functionConfiguration);
            //初始化引擎
            int errorCode;
            errorCode = faceEngine.init(engineConfiguration);
            if (errorCode != ErrorInfo.MOK.getValue()) {
                System.out.println("初始化引擎失败");
            }
        }

    /***
     * 人脸识别
     * @param file 人脸照片文件
     * @return 返回识别到的人脸list
     */
    public List<FaceInfo> detectFaces(File file){
        ImageInfo imageInfo = getRGBData(file);
        List<FaceInfo> faceInfoList = new ArrayList<>();
        FunctionConfiguration configuration = new FunctionConfiguration();
        configuration.setSupportAge(false);
        configuration.setSupportFace3dAngle(false);
        configuration.setSupportGender(false);
        configuration.setSupportLiveness(true);
        faceEngine.detectFaces(imageInfo.getImageData(),
                imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getImageFormat(),
                faceInfoList);
        if(faceInfoList.isEmpty()) {
            boolean isDelete = file.delete();
            if(!isDelete){
                System.out.println("File has not deleted");
            }
        }
        if(faceInfoList.size()>1) {
            return faceInfoList;
        }
        faceEngine.process(imageInfo.getImageData(),imageInfo.getWidth(), imageInfo.getHeight(),imageInfo.getImageFormat(),
                faceInfoList,configuration);
        return faceInfoList;
    }

    /***
     * 提取人脸特征
     * @param file 人脸照片文件
     * @param faceInfoList 识别到的人脸list
     * @return 返回提取到的人脸特征
     */
    public byte[] extractFaceFeature(File file,List<FaceInfo> faceInfoList){
        try {
            ImageInfo imageInfo = getRGBData(file);
            FaceFeature faceFeature = new FaceFeature();
            faceEngine.extractFaceFeature(imageInfo.getImageData(),
                    imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getImageFormat(),
                    faceInfoList.get(0), faceFeature);
            byte[] bytes = faceFeature.getFeatureData();
            boolean isDelete = file.delete();
            if(!isDelete){
                System.out.println("File has not deleted");
            }
            return bytes;
        }catch(Exception e){
            return null;
        }
    }
//    /***
//     * 批量提取人脸特征
//     * @param file 人脸照片文件
//     * @param faceInfoList 识别到的人脸list
//     * @return 返回提取到的人脸特征list
//     */
//    public List<byte[]> extractFaceFeatures(File file,List<FaceInfo> faceInfoList){
//        try {
//            List<byte[]> bytesList = new ArrayList<>();
//            File faceImage = file;
//            ImageInfo imageInfo;
//            for(int t =0;t<1000;t++){
//                if(faceImage.canRead()) {
//                    imageInfo = getRGBData(faceImage);
//                    for(int i = 0;i < faceInfoList.size();i++){
//                        byte[] bytes;
//                        FaceFeature faceFeature = new FaceFeature();
//                        faceEngine.extractFaceFeature(imageInfo.getImageData(),
//                                imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getImageFormat(),
//                                faceInfoList.get(i), faceFeature);
//                        bytes = faceFeature.getFeatureData();
//                        bytesList.add(bytes);
//                    }
//                    break;
//                }
//            }
//            faceImage.delete();
//            return bytesList;
//        }catch(Exception e){
//            return null;
//        }
//    }

    /***
     * 对比人脸
     * @param targetFaceFeature 目标人脸
     * @param sourceFaceFeature 库中的人脸
     * @return 返回相似度
     */
    public float compareFaceFeature(FaceFeature targetFaceFeature,FaceFeature sourceFaceFeature){
        int errorCode;
        FaceSimilar faceSimilar = new FaceSimilar();
        errorCode=faceEngine.compareFaceFeature(targetFaceFeature,sourceFaceFeature, CompareModel.LIFE_PHOTO,faceSimilar);
        if(errorCode == 0) {
            return faceSimilar.getScore();
        } else {
            return 0;
        }
    }

//    /***
//     * 多人脸对比
//     * @param targetMapList
//     * @param sourceMapList
//     * @return
//     */
//    public List<String> compareFaceFeatures(List<Map<String,Object>> targetMapList, List<Map<String,Object>> sourceMapList,double similar){
//        int errorCode;
//        FaceSimilar faceSimilar = new FaceSimilar();
//        Map targetMap;
//        Map sourceMap;
//        List<String> result = new ArrayList<>();
//        byte[] bytes;
//        for(int i = 0;i < targetMapList.size();i++){
//            targetMap = targetMapList.get(i);
//            bytes = (byte[]) targetMap.get("faceFeature");
//            FaceFeature targetFaceFeature = new FaceFeature(bytes);
//            for(int j = 0;j < sourceMapList.size();j++){
//                sourceMap = sourceMapList.get(j);
//                bytes = (byte[])sourceMap.get("faceFeature");
//                FaceFeature sourceFaceFeature = new FaceFeature(bytes);
//                errorCode=faceEngine.compareFaceFeature(targetFaceFeature,sourceFaceFeature, CompareModel.LIFE_PHOTO,faceSimilar);
//                if(errorCode == 0&&faceSimilar.getScore()>= similar){
//                    result.add((String)sourceMap.get("uid"));
//                }
//            }
//        }
//        return result;
//    }

    /***
     * 活体检测
     * @return 返回错误码
     */
    public int getLiveness(){
        int errorCode;
        List<LivenessInfo> livenessInfoList = new ArrayList<>();
        errorCode = faceEngine.getLiveness(livenessInfoList);
        if(errorCode == 0) {
            return livenessInfoList.get(0).getLiveness();
        } else {
            return 5;
        }
    }

}
